package com.bos.controller;

import com.bos.controller.base.BaseController;
import com.bos.controller.base.imp.BaseControllerImp;
import com.bos.domain.Region;
import com.bos.domain.Subarea;
import com.bos.service.IRegionService;
import com.bos.service.ISubareaService;
import com.bos.utils.BOSUtil;
import com.bos.utils.HibernateUtils;
import com.bos.utils.PageBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author Administrator
 */
@Controller
/*解决hibernate的查询条件叠加的问题方法一就是设置该controller为多利，方法2就是每次进入分页方法都清除detachedCriteria之前的
* 查询条件*/
//@Scope("prototype")
public class SubareaController extends BaseControllerImp<Subarea> implements BaseController<Subarea> {

    @Autowired
    private IRegionService regionService;

    @Autowired
    private ISubareaService subareaService;

    private final String LIST="page/base/subarea";

       @Autowired
    public SubareaController(PageBean pageBean) {
        super(pageBean);
    }

    @RequestMapping(value = "/listRegions",method = RequestMethod.POST)
    @ResponseBody
    public String listRegion(String q){
        List<Region> regions = null;
        if (StringUtils.isNotBlank(q) && q !=null){
            regions = regionService.findAllByq(q);

        }else {
            regions=regionService.findAll();
        }
        return java2json(regions,new String[]{"citycode","subareas"});
    }

    @RequestMapping(value = "/addSubarea",method = RequestMethod.POST)
    public String addSubarea(Subarea subarea){
        subareaService.save(subarea);
        return "redirect:"+LIST;
    }

    @RequestMapping(value = "/SubareaPageQuery",method = RequestMethod.GET)
    @ResponseBody
    public String pageQuery(int page ,int rows, Subarea subarea){
        //每次进来清除之前的查询条件
        HibernateUtils.eraseCriteria(super.detachedCriteria);

        BOSUtil.getSession().setAttribute("SubareaPage",page);
        BOSUtil.getSession().setAttribute("SubareaRows",rows);
        if(StringUtils.isNotBlank(subarea.getAddresskey())){
            //添加关键字约束
            super.detachedCriteria.add(Restrictions.like("addresskey","%"+subarea.getAddresskey()+"%"));
        }
        Region region = subarea.getRegion();
        if (region!= null){
            String province = region.getProvince();
            String city = region.getCity();
            String district = region.getDistrict();
            //为关联的region表创建别名
            super.detachedCriteria.createAlias("region","r");
            //以下三个if添加省市区约束进行模糊查询
            if (StringUtils.isNotBlank(province)){
                super.detachedCriteria.add(Restrictions.like("r.province","%"+province+"%"));
            }
            if (StringUtils.isNotBlank(city)){
                super.detachedCriteria.add(Restrictions.like("r.city","%"+city+"%"));
            }
            if (StringUtils.isNotBlank(district)){
                super.detachedCriteria.add(Restrictions.like("r.district","%"+district+"%"));
            }
        }
        super.setPageAndRows(page,rows);
        regionService.pageQuery(super.pageBean);
        return java2json(new String[]{"currentPage", "pageSize", "detachedCriteria","subareas","decidedzone","name"});
    }


    @RequestMapping(value = "/exportXls",method = RequestMethod.GET)
    public String exportXls(HttpServletResponse res) throws IOException {
        boolean success = true;
        try {
            List<Subarea> subareas = subareaService.findAll();
            HSSFWorkbook excelWorkbook = createExcelFile(subareas);
            //将数据写会客户端
            String fileName = "分区数据.xls";

            //动态获取文件类型
            String contentType = BOSUtil.getSession().getServletContext().getMimeType(fileName);
            res.setContentType(contentType);
            res.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));

            ServletOutputStream outputStream = res.getOutputStream();
            excelWorkbook.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
            throw new RuntimeException("分区数据导出失败！");
        }
        return null;
    }

    private HSSFWorkbook createExcelFile(List<Subarea> subareas) {
        //创建一个Excel文件
        HSSFWorkbook hssfWorkbook=new HSSFWorkbook();
        //创建一个标签页
        HSSFSheet sheet = hssfWorkbook.createSheet("分区数据");

        //写入标题
        HSSFRow headRow = sheet.createRow(0);
        headRow.createCell(0).setCellValue("分区编号");
        headRow.createCell(1).setCellValue("省");
        headRow.createCell(2).setCellValue("市");
        headRow.createCell(3).setCellValue("区");
        headRow.createCell(4).setCellValue("关键字");
        headRow.createCell(5).setCellValue("起始号");
        headRow.createCell(6).setCellValue("终止号 ");
        headRow.createCell(7).setCellValue("单双号");
        headRow.createCell(8).setCellValue("位置");

        //写入正规数据
        for (Subarea subareaRow :subareas) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            dataRow.createCell(0).setCellValue(subareaRow.getId());
            dataRow.createCell(1).setCellValue(subareaRow.getRegion().getProvince());
            dataRow.createCell(2).setCellValue(subareaRow.getRegion().getCity());
            dataRow.createCell(3).setCellValue(subareaRow.getRegion().getDistrict());
            dataRow.createCell(4).setCellValue(subareaRow.getAddresskey());
            dataRow.createCell(5).setCellValue(subareaRow.getStartnum());
            dataRow.createCell(6).setCellValue(subareaRow.getEndnum());
            dataRow.createCell(7).setCellValue(subareaRow.getSingle());
            dataRow.createCell(8).setCellValue(subareaRow.getPosition());
        }
        return hssfWorkbook;
    }

    /**显示区域的分区情况
     * */
    @RequestMapping(value = "/findSubareasByRegion",method = RequestMethod.POST)
    @ResponseBody
    public String findSubareasByRegion(){
        List<Object> list = subareaService.finSubareasByRegion();
        String json = java2json(list, new String[]{});
        return json;
    }


}
